package com.hjm.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.hjm.common.exception.BusinessException;
import com.hjm.project.merchantInfo.annotation.FieldDefaultData;
import com.hjm.project.merchantInfo.annotation.FieldMapping;
import com.hjm.project.merchantInfo.annotation.QcfFieldMapping;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 数据映射处理类
 * author Gdd
 */
public class DataConvertor<T> {
    //需做映射的实体
    private T t;

    public DataConvertor(){
        try {
            //获取当前类的泛型实体类
            Type superclass = getClass().getGenericSuperclass();
            if (superclass instanceof Class) {
                throw new RuntimeException("未获取到需转换的实体类");
            } else {
                ParameterizedType parameterized = (ParameterizedType)superclass;
                Class<T> entityClass = (Class<T>) parameterized.getActualTypeArguments()[0];
                t = entityClass.newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 字段赋值
     * @param t
     * @param field
     */
    public void setValue(T t,Field field,Class<?> aClass,String value) throws Exception {
        field.setAccessible(true);
        //属性赋值
        if (aClass == Integer.class) {
            field.set(t,Integer.parseInt(value));
        } else if (aClass == String.class){
            field.set(t,String.valueOf(value));
        } else if (aClass == BigDecimal.class){
            field.set(t,new BigDecimal(value));
        } else if (aClass == Date.class){
            //field.set(t, DateUtils.timeStampToDate(Long.parseLong(value), "yyyy-MM-dd"));
            field.set(t, DateUtils.stampToTime(value));
        }
    }


    /**
     * 验证参数
     * @param column
     * @param isNotBlank
     * @param body
     * @return
     */
    public boolean valiParams(String column,boolean isNotBlank,boolean isNotNull,JSONObject body){
        //缺少映射的值
        if (!body.containsKey(column) && !isNotNull) {
            throw new BusinessException("参数错误,缺少字段[" + column + "]");
        }
        if (StringUtils.isBlank(body.getString(column))){
            //必传参数不可为空
            if (isNotBlank && !isNotNull) {
                throw new BusinessException("参数错误,[" + column + "]不可为空");
            } else {
                return true;
            }
        }
        return false;
    }



    /**
     * map参数自定义映射实体类
     *
     * @param body
     * @return
     */
    public T format(JSONObject body) throws Exception {
        try {
            //获取所有字段的注解
            for (Field field : t.getClass().getDeclaredFields()) {
                FieldMapping fieldMapping = field.getAnnotation(FieldMapping.class);
                QcfFieldMapping qcfFieldMapping = field.getAnnotation(QcfFieldMapping.class);
                FieldDefaultData fieldDefaultData = field.getAnnotation(FieldDefaultData.class);
                //字段名称
                String column = "";
                //字段值
                String value = "";
                //是否允许为空
                boolean isNotBlank = false;
                //是否允许为null
                boolean isNotNull = false;
                //字段对应java类型
                Class<?> aClass = null;
                if (fieldMapping != null) {         //商户映射自定义参数注解
                    column = fieldMapping.column().toUpperCase();
                    isNotBlank = fieldMapping.isNotBlank();
                    isNotNull = fieldMapping.isNotNull();
                    boolean valiResult = valiParams(column, isNotBlank,isNotNull, body);
                    if (valiResult) {
                        continue;
                    }
                    value = body.getString(column);
                    aClass = fieldMapping.javaType();
                } else if (qcfFieldMapping != null){
                    column = qcfFieldMapping.column();
                    isNotBlank = qcfFieldMapping.isNotBlank();
                    isNotNull = qcfFieldMapping.isNotNull();
                    boolean valiResult = valiParams(column, isNotBlank,isNotNull, body);
                    if (valiResult) {
                        continue;
                    }
                    value = body.getString(column);
                    aClass = qcfFieldMapping.javaType();
                } else if (fieldDefaultData != null){    //默认参数注解
                    value = fieldDefaultData.value();
                    aClass = fieldDefaultData.javaType();
                }
                setValue(t,field,aClass,value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BusinessException) {
                throw e;
            } else {
                throw new BusinessException("参数解析异常");
            }
        }
        return t;
    }





    public static void main(String[] args) throws Exception {
      /*  Map<String,Object> params = new HashMap<>();
        params.put("user_name","张三");
        params.put("user_age","24");
        params.put("user_sex","11");
        params.put("merno","848000000225");
        params.put("ind_category","");
        params.put("add_date",String.valueOf(new Date().getTime()));
        String s = JSONObject.toJSONString(params);
        Map<String,String> map = JSON.parseObject(s, Map.class);
        PayMerchant format = new DataConvertor<PayMerchant>() {}.format(map);
        System.out.println(JSONObject.toJSONString(format));*/

    }

}
